# frozen_string_literal: true

class Rule < ApplicationRecord
  include UuidGenerator

  module Status
    extend ConstantEnum

    CREATED = 'created'
    DEPLOYED = 'deployed'
    DEPRECATED = 'deprecated'
  end

  has_many :versions, class_name: 'RuleVersion', dependent: :delete_all
  has_many :entities, class_name: 'RuleEntity', dependent: :destroy
  has_one :draft_entity,
          -> { where stage: RuleEntity::Stage::DRAFT },
          class_name: 'RuleEntity'
  has_many :product_entities,
           -> { where stage: RuleEntity::Stage::PRODUCT },
           class_name: 'RuleEntity'

  # accepts_nested_attributes_for :entities, allow_destroy: false
  accepts_nested_attributes_for :draft_entity, allow_destroy: true

  scope :filter_type, ->(type) { where type: type if type.present? }
  scope :filter_name, ->(name) { where '`name` like ?', "%#{name}%" if name.present? }
  scope :filter_status, ->(status) { where status: status if status.present? }

  delegate :validate, :deploy, to: :draft
  delegate :fire, to: :current

  before_create :init_status
  before_destroy :only_destroy_created_rule

  validates :type, presence: true
  validates :name, presence: true
  validates :status, presence: true, inclusion: { in: Status.values }, allow_blank: true

  def current
    @current ||= current_version && entities.find_by(version: current_version)
  end

  def draft
    draft_entity || current
  end

  private

  def init_status
    self.status = Status::CREATED
  end

  def only_destroy_created_rule
    raise 'Unsupported operate.' unless status.eql?(Status::CREATED)
  end
end
